package com.edroid.droidhelper.pc.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.edroid.droidhelper.pc.bean.InstallLogBean;
import com.edroid.droidhelper.pc.util.HttpUtils;
import com.edroid.droidhelper.pc.util.Logger;
import com.edroid.droidhelper.pc.util.TextUtils;

/**
 * 装机日志管理
 * 
 * @author 建宾
 *
 */
public class InstallLogManager {
	static final Logger log = Logger.create(InstallLogManager.class.getSimpleName());

	private static InstallLogManager instance;
	
	public static synchronized InstallLogManager getInstance() {
		if(instance == null)
			instance = new InstallLogManager();
		return instance;
	}
	
	private Connection conn;
	
	
	public InstallLogManager() {
		try {
			Class.forName("org.sqlite.JDBC");
			conn = DriverManager.getConnection("jdbc:sqlite:" + AppGlobal.PATH_LOG_DB);
			
			int ret = conn.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS logs (" /*_id INTEGER PRIMARY KEY,*/
					+ "_id TEXT,"
					+ " userId TEXT,"
					+ " imei TEXT,"
					+ " model TEXT,"
					+ " manufacturer TEXT,"
					+ " hardware TEXT,"
					+ " osver TEXT,"
					+ " hostname TEXT,"
					+ " toolType TEXT,"
					+ " toolName TEXT,"
					+ " toolMac TEXT,"
					+ " toolIp TEXT,"
					+ " toolOs TEXT,"
					+ " appCount TEXT,"
					+ " appList TEXT,"
					+ " time TEXT,"
					+ " timeMills TEXT);");
			log.i("create table ret=" + ret);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		log.i("close Connection ...");
		try {
			conn.close();
		} catch (Exception e) {
		}
	}
	
	private void clearUploadedFromDB(List<InstallLogBean> list) {
		try {
			Statement stat = conn.createStatement();
			synchronized (instance) {
				for(InstallLogBean e : list) {
					try {
						int ret = stat.executeUpdate("DELETE FROM logs WHERE _id=\'" + e._id + "\';");
						log.i("del " + e._id + " ret=" + ret);
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			}
			stat.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		
	public void upload() {
		List<InstallLogBean> list = querryAll();
		if(list != null) {
			JSONArray array = new JSONArray();
			for(InstallLogBean e : list) {
				array.put(e.toJsonObject());
			}
			
			try {
				HttpPost post = new HttpPost(AppGlobal.API_URL_TOOLLOGS);
				String data = array.toString();
				
//				log.i(AppGlobal.API_URL_TOOLLOGS);
//				log.i(data);
//				
//				List<InstallLogBean> list2 = InstallLogBean.parse(data);
//				System.out.println(list2);
				
				HttpEntity entity = new StringEntity(data, HttpUtils.CHARSET);
	  			post.setEntity(entity);
				
				long t0 = System.currentTimeMillis();
//				String ret = HttpUtils.post(post);

				String ret = HttpUtils.post(AppGlobal.API_URL_TOOLLOGS,
						new BasicNameValuePair("json", data));
				
				System.out.println(ret);
				
				if (TextUtils.isEmpty(ret)) {
					JSONObject json = new JSONObject(ret);
					int code = json.getInt("code");
					if (code == 200) {
						log.i("install logs upload success, spend time=" + (System.currentTimeMillis() - t0));

						clearUploadedFromDB(list);
					} else {
						log.e("upload fail, code=" + code + " msg=" + json.optString("msg"));
					}
				} else {
					log.e("upload fail, server error!");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private List<InstallLogBean> querryAll() {
		List<InstallLogBean> list = null;
		try {
			Statement stat = conn.createStatement();
			
			synchronized (instance) {
				ResultSet ret = stat.executeQuery("SELECT * FROM logs;");
				if(ret.next()) {
					list= new ArrayList<InstallLogBean>();
					do {
						InstallLogBean bean = new InstallLogBean();
						bean._id = ret.getString(1);
						bean.userId = ret.getString(2);
						bean.imei = ret.getString(3);
						bean.model = ret.getString(4);
						bean.manufacturer = ret.getString(5);
						bean.hardware = ret.getString(6);
						bean.osver = ret.getString(7);
						bean.hostname = ret.getString(8);
						bean.toolType = ret.getString(9);
						bean.toolName = ret.getString(10);
						bean.toolMac = ret.getString(11);
						bean.toolIp = ret.getString(12);
						bean.toolOs = ret.getString(13);
						bean.appCount = ret.getString(14);
						bean.appList = ret.getString(15);
						bean.time = ret.getString(16);
						bean.timeMills = ret.getString(17);
						list.add(bean);
					} while (ret.next());

					log.i("get logs from db suc, count=" + list.size());
				}
				ret.close();
			}
			
			stat.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return list;
	}
	
	public boolean add(InstallLogBean bean) {
		if(conn == null)
			return false;
		
		try {
			String sql = String.format("INSERT INTO logs VALUES("
					+ "\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\',"
					+ "\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\'"
					+ ");",
					String.valueOf(System.currentTimeMillis()), 
					bean.userId, bean.imei, bean.model, bean.manufacturer, bean.hardware, bean.osver, bean.hostname,
					bean.toolType, bean.toolName, bean.toolMac, bean.toolIp, bean.toolOs,
					bean.appCount, bean.appList, bean.time, bean.timeMills);
			log.i("insert:" + sql);
			
			Statement stat = conn.createStatement();
			synchronized (instance) {
				int ret = stat.executeUpdate(sql);
				log.i("ret=" + ret);
			}
			stat.close();
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
}
